package client

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io"
	"io/ioutil"
	"log"
)

func Client() {

	//读取解析三方自签名证书
	ca_b, _ := ioutil.ReadFile("thrid.crt")
	block, _ := pem.Decode(ca_b)
	ca, _ := x509.ParseCertificate(block.Bytes)

	//添加到证书列表
	pool := x509.NewCertPool()
	pool.AddCert(ca)

	//客户端证书
	cert, err := tls.LoadX509KeyPair("client.crt", "client.key")

	if err != nil {
		fmt.Println(err)
	}

	config := tls.Config{
		//证书链
		Certificates: []tls.Certificate{cert},
		//信任证书列表
		RootCAs: pool,
		//否验证服务器的证书链和主机名
		InsecureSkipVerify: false,
	}
	conn, err := tls.Dial("tcp", "localhost:22443", &config)
	if err != nil {
		log.Fatalf("client: dial: %s", err)
	}
	defer conn.Close()
	log.Println("client: connected to: ", conn.RemoteAddr())

	state := conn.ConnectionState()
	for _, v := range state.PeerCertificates {
		fmt.Println(x509.MarshalPKIXPublicKey(v.PublicKey))
		fmt.Println(v.Subject)
	}
	log.Println("client: handshake: ", state.HandshakeComplete)
	log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)

	message := "Hello\n"
	n, err := io.WriteString(conn, message)
	if err != nil {
		log.Fatalf("client: write: %s", err)
	}
	log.Printf("client: wrote %q (%d bytes)", message, n)

	reply := make([]byte, 256)
	n, err = conn.Read(reply)
	log.Printf("client: read %q (%d bytes)", string(reply[:n]), n)
	log.Print("client: exiting")
}

